package com.cskaoyan.market.controller;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.Encoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Map;


@WebServlet("/wx/storage/fetch/*")
public class WXStorageController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        byte[] bytes = new byte[8192];
        int readCount=0;
        ServletOutputStream outputStream = resp.getOutputStream();
        String path = req.getRequestURI().replace(req.getContextPath() + "/wx/storage/fetch/",
                (String) ((Map) req.getServletContext().getAttribute("path")).get("filePath") + "/");

        String decode = URLDecoder.decode(path, "UTF-8");
        File file = new File(decode);

        //todo   要进行编码转换
        FileInputStream fileInputStream = new FileInputStream(file);
        if(file.exists()&&file.isFile() ){
            while((readCount=fileInputStream.read(bytes))!=-1)
            {
                outputStream.write(bytes,0,readCount);
            }
            return;
        }
        resp.setStatus(404);
    }
}
